import {
    PLUGIN_PATH,
    getPlayerData,
    storagePlayerData,
    ensureGroupAndPlayerExist,
    formatCurrency,
    getConfig,
    checkPermission
} from "../function/function.js";
import puppeteer from "../../../lib/puppeteer/puppeteer.js";

export class TrainSlave extends plugin {
    constructor() {
        super({
            name: '[Sm]训练奴隶',
            dsc: '训练奴隶以提升其价值',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^[#\/]训练\s*(\d+)?$/, fnc: 'trainSlave' },
                { reg: /^[#\/]一键训练$/, fnc: 'trainAllSlaves' }
            ]
        })
    }

    async trainSlave(e) {
        if (!e.isGroup) return e.reply(['该功能只能在群内使用']);
        const ID = [e.user_id, e.group_id];

        // 确保群组和玩家数据存在
        ensureGroupAndPlayerExist(ID[1], ID[0]);


        // 获取目标奴隶ID
        let slave = e.at;
        if (!slave) slave = e.msg.replace(/#|\/|训练|\s/g, '');
        slave = parseInt(slave);

        try {
            const userData = await getPlayerData(ID[1], ID[0]);
            if (!userData.slave.includes(slave)) {
                return e.reply(['你不是该奴隶的主人']);
            }

            const config = getConfig();
            const currentTime = Math.floor(Date.now() / 1000);

            // 检查奴隶的训练冷却时间
            const slaveData = await getPlayerData(ID[1], slave);
            if (!checkPermission(e) && slaveData.lastTrainedTime && currentTime - slaveData.lastTrainedTime < config.training.cooldown) {
                const remainingTime = config.training.cooldown - (currentTime - slaveData.lastTrainedTime);
                const hours = Math.floor(remainingTime / 3600);
                const minutes = Math.floor((remainingTime % 3600) / 60);
                return e.reply([`该奴隶还在休息中，剩余时间：${hours}小时${minutes}分钟`]);
            }

            const trainingCost = Math.floor(slaveData.value * config.training.costRate);

            if (userData.currency < trainingCost) {
                return e.reply([`训练需要${trainingCost}金币，你的余额不足`]);
            }

            // 随机训练结果
            if (Math.random() < config.training.successRate) {
                const valueIncrease = Math.floor(slaveData.value * config.training.valueIncreaseRate);
                slaveData.value = formatCurrency(slaveData.value + valueIncrease);
                userData.currency = formatCurrency(userData.currency - trainingCost);
                slaveData.lastTrainedTime = currentTime;  // 更新奴隶的训练时间

                await storagePlayerData(ID[1], slave, slaveData);
                await storagePlayerData(ID[1], ID[0], userData);

                const memberInfo = (await Bot.pickGroup(ID[1]).getMemberMap()).get(slave);
                return e.reply([
                    segment.at(ID[0]),
                    `\n训练成功！消耗${trainingCost}金币\n`,
                    `${memberInfo.nickname}的身价提升${valueIncrease}，现在为${slaveData.value}金币`
                ]);
            } else {
                userData.currency = formatCurrency(userData.currency - trainingCost);
                slaveData.lastTrainedTime = currentTime;  // 即使失败也要更新训练时间

                await storagePlayerData(ID[1], slave, slaveData);
                await storagePlayerData(ID[1], ID[0], userData);

                return e.reply([
                    segment.at(ID[0]),
                    `\n训练失败...\n`,
                    `消耗${trainingCost}金币\n`,
                    `奴隶身价未提升`
                ]);
            }
        } catch (error) {
            logger.error('处理训练请求时出错:', error);
            return e.reply(['处理请求时出错，请稍后再试']);
        }
    }

    async trainAllSlaves(e) {
        if (!e.isGroup) return e.reply(['该功能只能在群内使用']);
        const ID = [e.user_id, e.group_id];

        ensureGroupAndPlayerExist(ID[1], ID[0]);

        try {
            const userData = await getPlayerData(ID[1], ID[0]);
            if (!userData.slave || userData.slave.length === 0) {
                return e.reply(['你还没有奴隶可以训练']);
            }

            const config = getConfig();
            const currentTime = Math.floor(Date.now() / 1000);
            const results = [];
            let totalCost = 0;
            let successCount = 0;

            const memberInfoList = Object.fromEntries([...await Bot.pickGroup(ID[1]).getMemberMap()]);

            // 遍历所有奴隶
            for (const slaveId of userData.slave) {
                const slaveData = await getPlayerData(ID[1], slaveId);
                const slaveName = memberInfoList[slaveId]?.nickname || slaveId;

                if (!checkPermission(e) && slaveData.lastTrainedTime && currentTime - slaveData.lastTrainedTime < config.training.cooldown) {
                    const remainingTime = config.training.cooldown - (currentTime - slaveData.lastTrainedTime);
                    const hours = Math.floor(remainingTime / 3600);
                    const minutes = Math.floor((remainingTime % 3600) / 60);
                    results.push({
                        name: slaveName,
                        avatar: `https://q1.qlogo.cn/g?b=qq&nk=${slaveId}&s=160`,
                        result: '休息中',
                        valueChange: 0,
                        currentValue: slaveData.value,
                        status: 'resting',
                        remainingTime: `${hours}小时${minutes}分钟`
                    });
                    continue;
                }

                const trainingCost = Math.floor(slaveData.value * config.training.costRate);

                // 检查当前奴隶的训练费用是否足够
                if (userData.currency < trainingCost) {
                    results.push({
                        name: slaveName,
                        avatar: `https://q1.qlogo.cn/g?b=qq&nk=${slaveId}&s=160`,
                        result: '金币不足',
                        valueChange: 0,
                        currentValue: slaveData.value,
                        status: 'failed'
                    });
                    continue;
                }

                // 扣除训练费用
                userData.currency = formatCurrency(userData.currency - trainingCost);
                totalCost += trainingCost;

                // 为每个奴隶单独进行随机判定
                if (Math.random() < config.training.successRate) {
                    const valueIncrease = Math.floor(slaveData.value * config.training.valueIncreaseRate);
                    slaveData.value = formatCurrency(slaveData.value + valueIncrease);
                    results.push({
                        name: slaveName,
                        avatar: `https://q1.qlogo.cn/g?b=qq&nk=${slaveId}&s=160`,
                        result: '训练成功',
                        valueChange: valueIncrease,
                        currentValue: slaveData.value,
                        status: 'success'
                    });
                    successCount++;
                } else {
                    results.push({
                        name: slaveName,
                        avatar: `https://q1.qlogo.cn/g?b=qq&nk=${slaveId}&s=160`,
                        result: '训练失败',
                        valueChange: 0,
                        currentValue: slaveData.value,
                        status: 'failed'
                    });
                }

                slaveData.lastTrainedTime = currentTime;
                await storagePlayerData(ID[1], slaveId, slaveData);
            }

            // 保存更新后的用户数据
            await storagePlayerData(ID[1], ID[0], userData);

            // 生成训练结果图片
            const image = await puppeteer.screenshot('训练结果', {
                tplFile: 'plugins/Slave-Market/resources/html/training/index.html',
                filePath: `${PLUGIN_PATH}/resources/`,
                summary: {
                    totalSlaves: userData.slave.length,
                    successCount,
                    failCount: userData.slave.length - successCount,
                    totalCost,
                    remainingCurrency: userData.currency
                },
                results
            });

            return e.reply([
                segment.at(ID[0]),
                image
            ]);

        } catch (error) {
            logger.error('处理一键训练请求时出错:', error);
            return e.reply(['处理请求时出错，请稍后再试']);
        }
    }
} 